﻿namespace MonetDbDataProvider
{
    using System;
    using System.Data;

    using MonetDbDataProvider.Mapi;

    public class MonetDbConnection : IDbConnection
    {
        public MonetDbConnection(string connectionString)
        {
            this.ConnectionString = connectionString;
            this.State = ConnectionState.Closed;
        }

        public string ConnectionString { get; set; }

        public int ConnectionTimeout { get; private set; }

        public string Database { get; private set; }

        public ConnectionState State { get; private set; }

        public void Dispose()
        {
            this.Close();
        }

        public IDbTransaction BeginTransaction()
        {
            throw new System.NotImplementedException();
        }

        public IDbTransaction BeginTransaction(IsolationLevel il)
        {
            throw new System.NotImplementedException();
        }

        public void Close()
        {
            if (this.MonetDbSocket != null)
                this.MonetDbSocket.Close();

            this.State = ConnectionState.Closed;
        }

        public void ChangeDatabase(string databaseName)
        {
            if (this.State == ConnectionState.Open) this.Close();

            var connectionString = new ConnectionString(this.ConnectionString);
            connectionString.Database = databaseName;

            this.ConnectionString = connectionString.ToString();
            this.Open();
        }

        public IDbCommand CreateCommand()
        {
            throw new System.NotImplementedException();
        }

        public void Open()
        {
            if (this.State != ConnectionState.Closed)
                throw new InvalidOperationException("A connection is already open.");

            this.State = ConnectionState.Connecting;

            this.MonetDbSocket = MapiSocketFactory.GetSocket(new ConnectionString(this.ConnectionString));
        }

        internal void ExecuteSql(string sql)
        {
            this.MonetDbSocket.ExecuteCommand(sql);
        }

        internal MapiSocket MonetDbSocket { get; set; }
    }
}
